# -*- coding: utf-8 -*-
"""
@Time : 2021/8/26 0:00
@Author : 华大大不是大大
@File : file_util.py
"""
import csv
import json
import os
import yaml


# 获取项目路径
def get_os_path():
    return os.path.abspath(os.getcwd().split('util')[0])


# 往extract文件中写数据
def write_extract(data):
    with open(get_os_path() + '/config/extract.yml', mode='a') as f:
        yaml.dump(data=data, stream=f, allow_unicode=True)


# 读取extract.yaml文件中的数据（该文件层级只有一级）
def read_extract(data):
    with open(get_os_path() + '/config/extract.yml', encoding="utf-8") as f:
        value = yaml.load(stream=f, Loader=yaml.FullLoader)
        return value[data]


# 测试用例执行前先清除extract.yaml文件内容
def clear_extract():
    with open(get_os_path() + '/config/extract.yml', mode='w') as f:
        f.truncate()


# 读取yaml文件的内容
def read_yaml(file_path):
    with open(get_os_path() + file_path, encoding="utf-8") as f:
        value = yaml.load(stream=f, Loader=yaml.FullLoader)
        value_keys = dict(*value).keys()
        if "parametrize" in value_keys:
            value = analysis_parametrize(*value)
            return value
        else:
            return value


# 读取csv文件数据并返回列表
def read_csv_file(csv_path):
    csv_data_list = []
    with open(get_os_path() + csv_path, encoding="utf-8") as f:
        csv_data = csv.reader(f)
        for i in csv_data:
            csv_data_list.append(i)
    return csv_data_list


def analysis_parametrize(case_info):
    case_info_keys = dict(case_info).keys()
    if "parametrize" in case_info_keys:
        for key, value in dict(case_info['parametrize']).items():
            case_info_str = json.dumps(case_info)
            key_list = str(key).split('-')
            csv_data_list = read_csv_file(value)
            one_row_csv_data = csv_data_list[0]
            length_flag = True
            for csv_data in csv_data_list:
                if len(csv_data) != len(one_row_csv_data):
                    length_flag = False
                    break
            new_case_info = []
            if length_flag:
                for x in range(1, len(csv_data_list)):
                    temp_case_info = case_info_str
                    for y in range(0, len(csv_data_list[x])):
                        if csv_data_list[0][y] in key_list:
                            temp_case_info = temp_case_info.replace("$csv{" + csv_data_list[0][y] + "}",
                                                                    csv_data_list[x][y])
                    new_case_info.append(json.loads(temp_case_info))
            return new_case_info
    else:
        return case_info
